import React, { useEffect, useRef, useState } from "react";
import styled from 'styled-components'
// import { Chart, LineAdvance} from 'bizcharts';
import { debounce, downloadDocument, readExcel, solveSpecificStr } from '@/util/util'
import { Modal, Form, Button, Input, Tag } from "@arco-design/web-react";
import jiangsu from "./jiangsu.json";
import * as echarts from 'echarts';
import 'echarts-gl'

const FormItem = Form.Item;
// 注册江苏省数据
echarts.registerMap('江苏', JSON.parse(JSON.stringify(jiangsu)))

export interface IJSMapCharts {
    id: string;
    style?: Record<string, string>;
    isDeviceShow?: boolean;
    onAreaClick?: (location: string) => void
}

type EChartsOption = echarts.MapSeriesOption;

const Wrapper = styled.div`
    position: relative;
    width: 100%;
    height: 100%;
`;

// echarts.use([echarts.MapChart]);
interface IDeviceInfo {
    deviceId: number;
    deviceName: string;
    deviceNumber: string;
    address: string;
    ip: string;
    state: string;
    createTime: string | number;
}

const JSMapCharts = (props: IJSMapCharts) => {

    const { id, style, onAreaClick, isDeviceShow = true } = props;
    const chartRef = useRef<echarts.EChartsType | null>();
    const hoverAreaRef = useRef<string>('');
    const [ visible, setVisible ] = useState<boolean>(false);
    const [ deviceInfo, setDeviceInfo ] = useState<IDeviceInfo | {}>({});

    const label = {
        deviceId: '设备ID',
        deviceName: '设备名称',
        deviceNumber: '设备编号',
        address: '设备地址',
        ip: '设备IP',
        state: '设备状态',
        createTime: '设备创建时间',
    };
    // 每个地级市的省会经纬度坐标
    const gdGeoCoordMap = {
        "南京市": [118.767413,32.041544],
        "无锡市": [120.301663,31.574729],
        "徐州市": [117.184811,34.261792],
        "常州市": [119.946973,31.772752],
        "苏州市": [120.619585,31.299379],
        "南通市": [120.864608,32.016212],
        "连云港市": [119.178821,34.600018],
        "淮安市": [119.021265,33.597506],
        "盐城市": [120.139998,33.377631],
        "扬州市": [119.421003,32.393159],
        "镇江市": [119.452753,32.204402],
        "泰州市": [119.915176,32.484882],
        "宿迁市": [118.275162,33.963008],
    }
    const geo3D = {
        map: '江苏',                   // 地图类型。
        boxDepth: 80,                 // 三维地理坐标系组件在三维场景中的深度
        regionHeight: 4,              // 三维地图每个区域的高度
        zoom: 15,
        tooltip: {
            show: true,
        },
        // 用于鼠标的旋转，缩放等视角控制
        viewControl: {
            autoRotate: false,          // 是否开启视角绕物体的自动旋转查看
            rotateSensitivity: 4,       // 旋转操作的灵敏度，值越大越灵敏。支持使用数组分别设置横向和纵向的旋转灵敏度。
            zoomSensitivity: 1,         // 缩放操作的灵敏度，值越大越灵敏。
            panSensitivity: 1,          // 平移操作的灵敏度，值越大越灵敏。支持使用数组分别设置横向和纵向的平移灵敏度
            alpha: 30,                  // 视角绕 x 轴，即上下旋转的角度。配合 beta 可以控制视角的方向。
            beta: -52,                  // 视角绕 y 轴，即左右旋转的角度。
            maxBeta: 90,                // 左右旋转的最大 beta 值。即视角能旋转到达最右的角度。
            distance: 30,
        },
        // 三维地理坐标系组件 中三维图形的视觉属性，包括颜色，透明度，描边等
        itemStyle: {
            opacity: 0.5,
            color: '#081c80a6',  // 地图颜色
            borderWidth: 1,           // 分界线wdith
            borderColor: '#459bca',   // 分界线颜色
        },
        // 是否显示地面
        groundPlane: {
            show: true,
            color: '#080b1ae3',
        },
        label: {
            show: true,
            color: 'white',
            fontSize: '16',
        },
        // 鼠标 hover 高亮时图形和标签的样式。
        emphasis: {
            disabled: false,
            label: {
                show: true,            // 是否显示高亮
                formatter: function (params) {
                    hoverAreaRef.current = params.name;
                    return params.name;
                },
                fontSize: '20',
                // fontFamily: 'STCaiyun',
            },
            itemStyle: {
                color: '#16298ba6'        // 地图高亮颜色
            }
        },
        // 光照相关的设置。
        light: {
            // 场景主光源的设置
            main: {
                color: '#fff',          // 主光源的颜色
                intensity: 1.5,         // 主光源的强度
                shadow: true,           // 主光源是否投射阴影
                shadowQuality: 'high',  // 阴影的质量
                // alpha: 55,           // 主光源绕 x 轴，即上下旋转的角度
                // beta: 4,             // 主光源绕 y 轴，即左右旋转的角度
            },
            // 全局的环境光设置
            ambient: {
                color: '#fff',  // 环境光的颜色
                intensity: 2    // 环境光的强度
            },
            ambientCubemap: {
                diffuseIntensity: 2,  // 漫反射的强度
                specularIntensity: 2, // 高光反射的强度
            },
        },
        
    }

    const options = {
        geo3D,
        series: isDeviceShow ? [
            {
                name: 'bar',
                type: `bar3D`,
                coordinateSystem: `geo3D`,
                barSize: 2,
                shading: "lambert",
                opacity: 1,
                bevelSize: 0.5,
                label: {
                    show: false,
                    color: 'black',
                },
                emphasis: {
                    disabled: false,
                    label: {
                        show: true,            // 是否显示高亮
                        formatter: function (params) {
                            hoverAreaRef.current = params.name;
                            return params.data.deviceName;
                        },
                        fontSize: '16',
                        color: 'white',
                    },
                    itemStyle: {
                        color: '#16298ba6'
                    }
                },
                data: Object.keys(gdGeoCoordMap).map((city, index) => {
                    return {
                        name: city,
                        deviceName: `工控机xs-${Math.floor(Math.random() * 5000)}`,
                        deviceId: index,
                        value: [ ...gdGeoCoordMap[city], 40 ],
                        itemStyle: { color: city === '南京市' ? '#e71313b2' : '#47ad1883' }
                    }
                })
            },
        ] : [],
    }

    useEffect(() => {

        
        const wrapper = document.querySelector(`#wrapper_${id}`)!;
        const chartDom = document.getElementById(`charts_${id}`)!;

        chartRef.current = echarts.init(chartDom);

        const debounceResize = debounce(chartRef.current.resize, 10);
        const obCallback = () => {
            debounceResize();
            // chartRef?.current?.resize();
        }
        const observer = new ResizeObserver(obCallback)
        const mapClick = (e) => {
            const cursorType = (document.querySelector('#charts_jsmap')?.children[0] as any)?.style?.cursor;
            if (cursorType === 'pointer') {
                onAreaClick && onAreaClick(hoverAreaRef.current);
            }
        }
        const symbolClick = (e) => {
            const deviceId = e?.data?.deviceId;
            const deviceName = e?.data?.deviceName;
            const color = e?.data?.itemStyle?.color || '#47ad1883';
            setDeviceInfo({
                deviceId,
                deviceName,
                deviceNumber: deviceName,
                address: 'Your home',
                ip: '127.0.0.5',
                state: color === '#47ad1883' ? '正常' : '故障', 
                createTime: '2023-05-02 12:23:05',
            })
            setVisible(true);
        }

        options && chartRef.current?.setOption(options);
        chartRef.current.getZr().on('click', mapClick)
        chartRef.current.on('click', symbolClick)
        observer.observe(wrapper)

        return () => {
            observer.unobserve(wrapper);
            observer.disconnect();
            chartRef.current?.getZr().off('click', mapClick)
            chartRef.current?.off('click', symbolClick)
        }
    }, [])

    return (
        <Wrapper style={{...(style || {})}} id={`wrapper_${id}`}>
            <div style={{ width: '100%', height: style?.height || '250px' }} id={`charts_${id}`}></div>
            <Modal
                title='设备详情'
                visible={visible}
                footer={<Button type="primary" onClick={() => setVisible(false)}>关闭</Button>}
                onCancel={() => setVisible(false)}
                maskClosable={true}
            >
                <Form>
                    {
                        Object.keys(deviceInfo).map((key, index) => {
                            const blackList = [ 'deviceId' ];
                            const value = deviceInfo[key];
                            return !blackList.includes(key) ? <FormItem key={key + `_${index}`} label={label[key]}>
                                {
                                    key === 'state' ?
                                    (value === '故障' ? <Tag  color='#f53f3f' >{ value }</Tag>  : <Tag  color='#7bc616' >{ value }</Tag>) :
                                    <Input disabled={true} value={ value }></Input>
                                }
                            </FormItem> : null
                        })
                    }
                </Form>
            </Modal>
        </Wrapper>
    )
}


export default JSMapCharts;